package net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpReceiveDemo01 {
    public static void main(String[] args) {
        try {

            DatagramSocket datagramSocket = new DatagramSocket(8888);

            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

            datagramSocket.receive(datagramPacket);

            String ipAddress = datagramPacket.getAddress().getHostAddress(); // 获取服务端的ip地址
            int port = datagramPacket.getPort(); // 获取服务端的端口
            byte[] content = datagramPacket.getData(); // 获取服务端的数据
            System.out.println(ipAddress + ":" + port + "==>" + new String(content, 0, datagramPacket.getLength()));

            datagramSocket.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
